const app = getApp()
import Dialog from '../miniprogram_npm/@vant/weapp/dialog/dialog';
module.exports = Behavior({
    methods: {
        showAuthDialog() {
            if (wx.getStorageSync('bk-token') && wx.getStorageSync('userInfo')) return true;
            Dialog.alert({
                selector: "#van-dialog",
                title: '登录授权',
                message: '监测到您尚未登录，将不能享受快捷点单，是否允许进行授权登录？',
                showCancelButton: true
            })
                .then(() => {
                    this.getUserInfoByAuth()
                    // on confirm
                })
                .catch(() => {
                    // on cancel
                });
        },
        /**
         * 获取sessionID，获取code、sessin_key
         */
        getSessionInfo() {
            return new Promise((resolve, reject) => {
                if (wx.getStorageSync('bk-token')) return reject();
                wx.login({
                    // timeout: 60000 * 60,
                    async success(res) {
                        if (res.code) {
                            const { data } = await app.requestAll({
                                url: 'user/getSessionId',
                                method: 'POST',
                                params: { code: res.code },
                                alert: false
                            })
                            wx.setStorageSync("sessionId", data.sessionId)
                            resolve()
                        } else {
                            console.log('登录失败！' + res.errMsg)
                        }
                    }
                })
            })
        },
        /**
         * 用户小程序登录
         */
        getUserInfoByAuth() {
            wx.getUserProfile({
                desc: '用于快捷登录',
                success: async (res) => {
                    const wxAuth = {
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        sessionId: wx.getStorageSync('sessionId')
                    }
                    const { data } = await app.requestAll({
                        url: 'user/authLogin',
                        method: 'POST',
                        params: wxAuth,
                    })
                    wx.setStorageSync('bk-token', data.token)
                    wx.setStorageSync('userInfo', data.user)
                    this.fecthData()
                }
            })
        },
    }
})